package com.cykj.service.impl;

import com.cykj.dto.ResponseDTO;
import com.cykj.entity.UserDO;
import com.cykj.mapper.UserMapper;
import com.cykj.service.IUserService;
import com.cykj.utils.JwtUtils;
import com.cykj.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;


@Service
public class UserServiceImpl implements IUserService{

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public ResponseDTO login(UserVO userVO) {
        // 通过账号获取用户
        UserDO userDO = userMapper.getUserByAccount(userVO);
        // 判断账号密码是否正确
        if (userDO ==  null || !userDO.getPassword().equals(userVO.getPassword())){
            return ResponseDTO.error("用户名或密码错误");
        }
        // 封装生成 jwt
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("userId", userDO.getUserId());          // 放入用户ID
        claims.put("username",userDO.getUsername());       // 放入用户名
        String jwt = JwtUtils.generateJwt(claims);         // 生成 jwt
        // jwt 存入 redis --> 有效期 30 分钟
        userDO.setPassword(null);   // 删除密码
        redisTemplate.opsForValue().set(jwt,userDO,30, TimeUnit.MINUTES);

        // 返回结果
        return ResponseDTO.success("登录成功",jwt);
    }

    @Override
    public ResponseDTO register(UserVO userVO) {
        // 通过账号获取用户
        UserDO userDO = userMapper.getUserByAccount(userVO);
        // 判断用户是否存在
        if (userDO != null){
            return ResponseDTO.error("用户已存在");
        }
        // 添加用户
        Integer re = userMapper.addUserByyUserVO(userVO);
        // 返回结果
        return  re > 0
                ? ResponseDTO.success("注册成功")
                : ResponseDTO.error("注册失败");
    }
}
